import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';

import { UserService } from './user.service';
import { take, map } from 'rxjs/operators';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private router: Router,
    private userService: UserService
  ) { }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    // return this.userService.isAuthenticated.pipe(take(1));
    let active = false;
    const auth = this.userService.isAuthenticated.pipe(take(1));
    auth.subscribe(auth => active = auth)
    if (!active) {
      console.log("can not activate, navigate to /login ~")
      this.router.navigate(['/login']);
    }
    return auth
  }
}
